package nku.csc364;

/* Raj Akula
 * Main.java
 *
 * Function to load from a datfile and place into a bianry tree
 * 
 */
 
 
import java.io.*;
import javax.swing.JOptionPane;

public class Main{
	
	// Main function
	public static void main(String... args){
		
		Person[] personArray = new Person[300]; // Decalre array of 300
		AVLTree avlTree = new AVLTree(); // Establish about a Binary Tree
		
		//Try to open file and place in the binary tree and array
		try {
			loadFileToArray(personArray, avlTree);
		} catch (IOException e) {
			displayError();
			System.exit(1);
		}
		// After loading file display functions given to user
		displayInitialDialog(personArray, avlTree);
	}
	
	// Mehtod to display error if it fails to loadfile and place into binary tree
	private static void displayError() {
		
		JOptionPane.showMessageDialog(null,
			"Error loading data base, program is stopping.", "Error",
				JOptionPane.ERROR_MESSAGE);
	}
	
	//Method to loadFile 
	private static void loadFileToArray(Person[] personArray, AVLTree avlTree) throws IOException {

		int arrayIdx = 0; // array to start loading file into binary search tree and place in array
		BufferedReader input = new BufferedReader(new FileReader("datafile.txt"));
		String line = null; // not declared within while loop
			
		//Read till nothing in file
		while ((line = input.readLine()) != null) {
			String[] lineArray = line.split("\t");	// split at a tab
			// break up line so place each elements into each field
			Person person = new Person(lineArray[1], lineArray[0],
					lineArray[2], lineArray[3], lineArray[4].charAt(0),
					lineArray[5]);
			
			System.out.println(person);
			personArray[arrayIdx] = person; // place in array
			Index temp = new Index(arrayIdx, person.getSsn());
			avlTree.insert(temp, person.getSsn()); // place in tree
			arrayIdx++; // reading for next element
		}
	}
	
	// Method to display dialog for user
	private static void displayInitialDialog(Person[] personArray, AVLTree avlTree) {
		
		int response = 4; // no of choices for suer
		String[] choices = { "Add", "Find", "Delete", "Exit" }; // choices for user
		
		// Run loop as long as the given response is not exit or -1 
		while (response != 3 || response == -1) {

			response = JOptionPane.showOptionDialog(null,
					"Select a database record operation  : ", "Database Application (CSC 364)", 0,
					JOptionPane.INFORMATION_MESSAGE, null, choices, choices[3]);

			// Add a record
			if (response == 0) {
					addRecord(personArray, avlTree);

			}
			// Find a record
			if (response == 1) {
					doFind(personArray, avlTree);
			}
			//Delete a record
			if (response == 2) {
					doDelete(personArray, avlTree);
			}
			//Exit the program
			if (response == 3 || response == -1) { // Exit
				
					doExit(personArray);
				
			}

		}

	}
	
	// Mehthod to add to binary tree
	public static void addRecord(Person[] personArray, AVLTree avlTree) {
		
		//check if space is available in the array to add into file
		if (isSpaceAvailable(personArray)){
			
			// If it is display dialog for adding a user
			AddRecordDialog dialog = new AddRecordDialog(null);
			// Gets a person from the dialog 
			Person person = dialog.getPerson();
			
			// if everything is go to go places person in array and binary search tree
			if (person != null){
				int idx = 0;
				for (int i = 0; i < personArray.length; i++) {
					if (personArray[i] == null) {
						personArray[i] = person;
						break;
					}
					idx++;
				}
				Index temp = new Index(idx, person.getSsn());
				avlTree.insert(temp, person.getSsn());
				
				JOptionPane.showMessageDialog(null,
					"Person has been added!!!", "Success",
					JOptionPane.INFORMATION_MESSAGE);
			}
		}
		// if no space in array then display appropriate message
		else{
			JOptionPane.showMessageDialog(null,
					"Sorry, database is out of space.", "Error",
					JOptionPane.ERROR_MESSAGE);
		}
	}
	
	// method to check if space available in array
	private static boolean isSpaceAvailable(Person[] personArray){
		boolean result = false;
		for (int i = 0; i < personArray.length; i++) {
			if (personArray[i] == null) {
				result = true; 
			}
		}
		return result;
	}
	
	// method to find a person in binary search tree
	public static void doFind(Person[] personArray, AVLTree avlTree) {
		
		// Use dialog box for social security number
		String ssn = JOptionPane.showInputDialog("Enter Social Security of user to find");

		// If not entering ssn then keep asking them
		while (ssn != null && !InputValidator.isSsnValidated(ssn)){
			ssn = JOptionPane.showInputDialog(null, "Please enter a valid social security number.");
		}
		
		// If it is valid and htey didn't click cancel then look through the array
		if (ssn != null && InputValidator.isSsnValidated(ssn)){
			String mesg = "Nothing found"; // Orignal message
			int idx;
			// Search tree
			Index temp = (Index) avlTree.find(ssn);
			if (temp != temp){
				idx = temp.getIndex();
			}
			else {
				idx = -1;
			}
			
			// If found in tree then get the data.
			if (idx != -1 && personArray[idx] != null) {
				Person person = personArray[idx];
				StringBuffer msg = new StringBuffer();
				msg.append("Last Name: " + person.getLastName() + "\n");
				msg.append("First Name: " + person.getFirstName() + "\n");
				msg.append("SSN: " + person.getSsn() + "\n");
				msg.append("Phone no.: " + person.getPhoneNo() + "\n");
				msg.append("Gender: " + person.getGender() + "\n");
				msg.append("Birth Date: " + person.getDob() + "\n");
				mesg = msg.toString();
			}
			//Return message to user about the data
			JOptionPane.showMessageDialog(null, mesg,
					"Search Results for: \"" + ssn + "\"", JOptionPane.INFORMATION_MESSAGE);
		}
		

	}
	
	// method to delete a element in the tree
	public static void doDelete(Person[] personArray, AVLTree avlTree) {
		
		//Same as find here... 
		String ssn = JOptionPane.showInputDialog("Enter Social Security of user to delete");
		while ( ssn != null && !InputValidator.isSsnValidated(ssn)){
			ssn = JOptionPane.showInputDialog(null, "Please enter a valid social secuirty number.");
		}
		
		
		if (ssn != null && InputValidator.isSsnValidated(ssn)){
			// Call search function here
			Index temp = (Index)avlTree.find(ssn);
			int idx;
			if (temp != null){
				idx = temp.getIndex();
			}
			else{
				idx = -1;
			}
				
			// Call search function here
			String mesg = "Nothing found to delete.";
			int confirmation = -1;
			
			if (idx != -1) {
				Person person = personArray[idx];
				StringBuffer msg = new StringBuffer();
				msg.append("Last Name: " + person.getLastName() + "\n");
				msg.append("First Name: " + person.getFirstName() + "\n");
				msg.append("SSN: " + person.getSsn() + "\n");
				msg.append("Phone no.: " + person.getPhoneNo() + "\n");
				msg.append("Gender: " + person.getGender() + "\n");
				msg.append("Birth Date: " + person.getDob() + "\n");
				mesg = msg.toString();
				
				//cehck if they really want to delete
				confirmation = JOptionPane.showConfirmDialog(null,
						mesg+ "\nAre you sure you want to delete the above user? "
								, "Search Results for \"" + ssn +"\"",
						JOptionPane.YES_NO_OPTION);
				
				//if yes set ssn to ********
				if (confirmation == 0){
					avlTree.delete(person.getSsn());
					personArray[idx].setSsn("********");
				}
				
			}
			//record not found.
			else{
				JOptionPane.showMessageDialog(null, mesg,
						"Search Results..for " + ssn, JOptionPane.INFORMATION_MESSAGE);
			}
		}
	}
	
	// method to do exit
	public static void doExit(Person[] personArray) {
		
		// Code used to write to file right before exit
		try {
			FileOutputStream fo = new FileOutputStream("datafile.txt");
			PrintStream ps = new PrintStream(fo);
			
			
			for (int i=0;i<personArray.length;i++){
				if (personArray[i]!=null && !personArray[i].getSsn().equals("********")){
					ps.println(personArray[i].toString());
				}
			}
		} 
		catch (Exception e) {// Catch exception if any
			e.printStackTrace();
		}
		System.exit(0);
	}
	
	
}